package com.wzy.springcloud.controller;

import com.wzy.springcloud.entities.CommonResult;
import com.wzy.springcloud.entities.Payment;
import com.wzy.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class PaymentController {
    @Autowired
    private PaymentService paymentService;
    @Value("${server.port}")
    private String serverPort;
    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("/payment/zipkin")
    public String paymentZipkin() {
        return "hi, i am paymentzipkin server fall back,wehlecome to atguigu ;";
    }

    /**
     * 插入方法
     *
     * @param payment
     * @return 插入的条数
     */
    @PostMapping(value = "/payment/create")
    public CommonResult creat(@RequestBody Payment payment) {
        System.out.println(payment);
        int result = paymentService.creat(payment);
        log.info(">>>>>>>>>>插入数据结果:{}", result);
        if (result > 0) {
            return new CommonResult(200, "插入数据成功,服务端口为:" + serverPort, result);
        }
        return new CommonResult(444, "插入失败", null);
    }

    @GetMapping("/payment/get/{id}")
    public CommonResult<Payment> get(@PathVariable("id") Long id) {
        Payment result = paymentService.getPaymentById(id);
        log.info(">>>>>>>>>>查询结果:{}", result);
        if (!StringUtils.isEmpty(result)) {
            return new CommonResult(200, "查询成功,服务端口为:" + serverPort, result);
        }
        return new CommonResult(444, "查询失败", null);
    }

    @GetMapping(value = "/payment/lb")
    public String getPaymentLB() {
        return serverPort;
    }

    @GetMapping("/payment/discovery")
    public Object discovery() {
        List<String> services = discoveryClient.getServices();
        services.forEach(s -> {
            log.info(">>>>>element{}", s);
        });
        List<ServiceInstance> instances = discoveryClient.getInstances("COLUD-PAYMENT-SERVICE");
        instances.forEach(s -> {
            log.info("{},{},{},{}", s.getServiceId(), s.getHost(), s.getPort(), s.getUri());
        });
        return this.discoveryClient;
    }

    @GetMapping("/payment/feign/timeout")
    public String paymentFeignTimeout() {
        try {
            TimeUnit.SECONDS.sleep(3);

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return serverPort;
    }
}
